//
//  myListController.m
//  Candy
//
//  Created by 牛魔王 on 2018/8/29.
//  Copyright © 2018年 庄文盛 All rights reserved.
//

#import "myListController.h"
#import "Header.h"
#import "ListView.h"
#import "YSHYSlideViewController.h"
#import "ListModel.h"
#import "ListViewVC.h"
#import "XHToast.h"
#define LISTCELL @"list"
#define WS(weakSelf) __weak __typeof(&*self)weakSelf = self

@interface myListController ()<UITableViewDelegate,UITableViewDataSource> {
    CGFloat _allMoney;
}
@property (nonatomic, strong) UITableView *listView;
@property (nonatomic, strong) UIButton *deleteBtn;
@property (nonatomic, strong) UILabel *income;
@property (nonatomic, strong) UIView *line;
@property (nonatomic, strong) NSMutableArray *listSource;
@property (nonatomic, strong) NSMutableArray *selArray;        // 储存选中的item
@property (nonatomic, strong) NSMutableArray *goingState;
@property (nonatomic, strong) NSMutableArray *compliteState;
@property (nonatomic, assign) int ifComplite;
@end

@implementation myListController

- (void)viewWillAppear:(BOOL)animated {
    [self getList];
    self.navigationController.navigationBar.translucent = false;
    self.navigationController.navigationBar.barTintColor=[UIColor whiteColor];
}

- (void)viewDidDisappear:(BOOL)animated {
    //设置导航栏背景图片为一个空的image，这样就透明了
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    
    //去掉透明后导航栏下边的黑边
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.listView];
    [self.view addSubview:self.income];
    [self.view addSubview:self.deleteBtn];
    [self.view addSubview:self.line];
    UIButton *back=[[UIButton alloc]init];
    UIImage *img=[UIImage imageNamed:@"Chevron"];
    [back setImage:img forState:UIControlStateNormal];
    //    back.frame=CGRectMake(0, 0, 12.5, 21);
    [back addTarget:self action:@selector(toIndexView) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem *left=[[UIBarButtonItem alloc]initWithCustomView:back];
    self.navigationItem.leftBarButtonItem=left;
    // self.tabBarController.tabBar.hidden=YES;
    self.editing=NO;
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    self.navigationController.navigationBarHidden=YES;
    [self.navigationController setNavigationBarHidden:NO];
    [self.listView registerNib:[UINib nibWithNibName:@"ListView" bundle:nil] forCellReuseIdentifier:LISTCELL];
  
   
    // Do any additional setup after loading the view.
}

- (NSMutableArray *)goingState {
    if (!_goingState) {
        _goingState = [NSMutableArray new];
    }
    return _goingState;
}

- (NSMutableArray *)compliteState {
    if (!_compliteState) {
        _compliteState = [NSMutableArray new];
    }
    return _compliteState;
}

- (UILabel *)income {
    if (!_income) {
        _income = [UILabel new];
        _income.text = [NSString stringWithFormat:@"合计葡萄 :"];
        _income.frame = CGRectMake(20, KSHEIGHT-50-64, 220, 40);
        _income.font = [UIFont systemFontOfSize:15];
    }
    return _income;
}

- (UIView *)line {
    if (!_line) {
        _line = [UIView new];
        _line.frame = CGRectMake(0,KSHEIGHT-60-64 , KSWITH, 1);
        _line.backgroundColor = [UIColor colorWithHexString:@"#DCDCDC"];
    }
    return _line;
}

- (UITableView *)listView {
    if (!_listView) {
        _listView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KSWITH, KSHEIGHT-60-64) style:UITableViewStylePlain];
        _listView.delegate = self;
        _listView.dataSource = self;
        _listView.rowHeight = 140.f;
    }
    return _listView;
}

- (UIButton *)deleteBtn {
    if (!_deleteBtn) {
        _deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_deleteBtn setBackgroundImage:[UIImage imageNamed:@"but 7"] forState:UIControlStateNormal];
        [_deleteBtn setTitle:@"移除" forState:UIControlStateNormal];
        _deleteBtn.frame = CGRectMake(KSWITH-110, KSHEIGHT-50-64, 90, 36);
        _deleteBtn.layer.masksToBounds = YES;
        _deleteBtn.layer.cornerRadius = 18;
        if (_listOrCollection == 1) {
            [_deleteBtn setTitle:@"切换" forState:UIControlStateNormal];
            [_deleteBtn addTarget:self action:@selector(changeState) forControlEvents:UIControlEventTouchDown];
        }
        else{
            [_deleteBtn setTitle:@"移除" forState:UIControlStateNormal];
            [_deleteBtn addTarget:self action:@selector(deleteAction) forControlEvents:UIControlEventTouchDown];
        }
    }
    return _deleteBtn;
}

- (NSMutableArray *)listSource {
    if (!_listSource) {
        _listSource = [NSMutableArray new];
    }
    return _listSource;
}

- (NSMutableArray *)selArray
{
    if (!_selArray) {
        self.selArray = [NSMutableArray array];
    }
    return _selArray;
}

- (void)deleteAction {
    NSIndexPath *path = [NSIndexPath new];
    for (int i = 0; i < self.selArray.count; i++) {
        path = self.selArray[i];
        [self deleteCollection:path];
    }
    
    [XHToast showCenterWithText:@"取消收藏"];
    NSLog(@"移除");
}

- (void)deleteCollection :(NSIndexPath *)path {
    [SVProgressHUD showWithStatus:@"loading"];
    ListModel *model = [ListModel new];
    model = self.listSource[path.row];
    NSDictionary *parameters = @{@"id":model.id, @"userId":@"a"};
    AFHTTPSessionManager* session=[AFHTTPSessionManager manager];
    session.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    [session POST:COLLECTION parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        [self.listSource removeObjectAtIndex:path.row];
        [self.selArray removeObject:path];
        [self.listView reloadData];
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败");
    }];
}

- (void)toIndexView{
    [[YSHYSlideViewController shareInstance] ppp];
    self.tabBarController.tabBar.hidden=NO;
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
     ListView *cell = [tableView dequeueReusableCellWithIdentifier:LISTCELL forIndexPath:indexPath];

    if (_listOrCollection == 1) {
        cell.state.hidden = NO;
    }
    else {
        cell.state.hidden = YES;
    }
    [cell.selectBtn setImage: [self.selArray containsObject:indexPath] ? [UIImage imageNamed:@"go"] : [UIImage imageNamed:@"Oval 15"] forState:UIControlStateNormal];
    [cell setCellValue:self.listSource[indexPath.row]];
    WS(weakSelf);
    __weak typeof(cell)weakCell = cell;
    cell.selectAction = ^{
        if ([weakSelf.selArray containsObject:indexPath]) {            // 判断cell显示是否是选中状态
            [weakCell.selectBtn setImage:[UIImage imageNamed:@"Oval 15"]forState:UIControlStateNormal];
            [weakSelf.selArray removeObject:indexPath];
            ListModel *model = [ListModel new];
            model = self.listSource[indexPath.row];
            _allMoney = _allMoney - model.amout.floatValue;
            self.income.text = [NSString stringWithFormat:@"合计葡萄：%.2f",_allMoney];
        }else {
            [weakCell.selectBtn setImage:[UIImage imageNamed:@"go"]forState:UIControlStateNormal];
            [weakSelf.selArray addObject:indexPath];
            ListModel *model = [ListModel new];
            model = self.listSource[indexPath.row];
            _allMoney = _allMoney + model.amout.floatValue;
            self.income.text = [NSString stringWithFormat:@"合计葡萄：%.2f",_allMoney];
        }
        
    };
    return cell;
}

- (void)getList {
    
    if (self.listOrCollection == 1) {
        [self list:HISTORY];
    }
    else {
        [self list:COLLECTION];
    }
    
}

- (void)list:(NSString *)url {
    AFHTTPSessionManager* session=[AFHTTPSessionManager manager];
    session.responseSerializer=[AFHTTPResponseSerializer serializer];
    NSDictionary *parameters = @{@"userId":[[NSUserDefaults standardUserDefaults] valueForKey:USERID]};
    [session GET:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"下载成功");
        
        id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSMutableArray  *arr = (NSMutableArray *)jsonObject;
        NSLog(@"%@",arr);
        [self.listSource removeAllObjects];
        for (NSDictionary *dic in arr) {
            ListModel *model = [ListModel mj_objectWithKeyValues:dic];
            [self.listSource addObject:model];
            if ([model.state isEqualToString:@"1"]) {
                [self.goingState addObject:model];
            }
            else {
                [self.compliteState addObject:model];
            }
        }
        [self.listView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"下载失败");
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    ListViewVC *list = [ListViewVC new];
    list.model = self.listSource[indexPath.row];
    if (list.model.user_id) {
        list.listOrTask = 2;
    }
    else {
        list.listOrTask = 1;
    }
  
    //设置导航栏背景图片为一个空的image，这样就透明了
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    
    //去掉透明后导航栏下边的黑边
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    [self.navigationController pushViewController:list animated:YES];
    
}

@end
